import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Button, Modal } from 'antd';
import PropTypes from 'prop-types';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import HandleModel from './handleModel';
import ExportModal from './exportModel';
import ConfirmDelModal from './confirmDelModal';
import { filterAuth } from '@/support/common';

const mapStateToProps = (state: any) => ({
  HandsetMng: state.HandsetMng,
  loading: state.loading.models['HandsetMng'],
  permissions: state?.menu?.permissions,
  user: state?.menu?.userProfile,
});
const expirationState = ['到期', '未到期'];
const calibrationState = ['有效', '即将到期', '已到期,宽限期内', '已到期,锁止'];
const shuttingReason = ['初始测试闭锁', '复测闭锁', '永久闭锁', '可恢复的闭锁'];
const errorReason = ['一般错误', '自检失败', '酒精锁不工作', '通信错误', '无感检测模块错误'];
class HandsetMng extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      modalVisible: false,
      formData: {},
      exportVisible: false,
      confirmVisible: false,
      checkRecord: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'HandsetMng/getFetchPage',
      payload: {
        url: '/msalcohollock/handhelds/page',
        ...formValues,
      },
    });
  }
  handleFormReset = (fields: any) => {
    this.setState({
      formValues: {},
    });
  };
  //  新增
  handleAdd = () => {
    this.setState({
      modalVisible: true,
      formData: {},
    });
  };

  //  编辑
  handleEdit = (record: any) => {
    this.setState({
      modalVisible: true,
      formData: record,
    });
  };
  closeModal = () => {
    this.setState({
      modalVisible: false,
      formData: {},
    });
  };
  //批量导入
  handleExport = () => {
    this.setState({
      exportVisible: true,
    });
  };
  closeExportModal = () => {
    this.setState({
      exportVisible: false,
    });
  };
  handleFreshPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'HandsetMng/getFetchPage',
      payload: {
        url: '/msalcohollock/handhelds/page',
        ...formValues,
      },
    });
  };

  //  删除
  handleDelete = (record: any) => {
    //先对手持机绑定状态进行查询，未绑定才能弹出二次确认框弹窗进行删除
    const { dispatch } = this.props;
    dispatch({
      type: 'HandsetMng/getData',
      payload: { url: `/msalcohollock/handhelds/binding/state/${record.code}` },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            confirmVisible: true,
            checkRecord: record,
          });
          // this.handleFreshPage()
        } else {
          message.error('手持机已绑定车辆，解绑后才可删除');
        }
      },
    });
  };
  closeConfirmModal = (ref = false) => {
    this.setState({
      confirmVisible: false,
      checkRecord: {},
    });
    if (ref) {
      this.handleFreshPage();
    }
  };
  // 删除前
  render() {
    const {
      HandsetMng: {
        pageData: { list, pagination },
      },
      loading,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    const { formValues, modalVisible, formData, exportVisible, confirmVisible, checkRecord } =
      this.state;
    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    };

    const searchItems = [
      {
        title: '手持机编号',
        type: 'input',
        key: 'code',
        maxLength: 50,
        style: {},
        rules: [
          {
            required: false,
            message: '请输入英文及数字!',
            pattern: '^[a-zA-Z0-9]*$',
          },
        ],
      },
      {
        title: '手持机名称',
        type: 'input',
        key: 'name',
        maxLength: 50,
        rules: [
          {
            required: false,
            // message: '请输入中英文及数字、特殊字符!',
            // pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\w]+$/,
            message: '不能输入空字符!',
            pattern: /^\S+$/,
          },
        ],
      },
      {
        title: '标定状态',
        type: 'select',
        key: 'calibrationState',
        selectOptions: [
          { label: '有效', value: 0 },
          { label: '即将到期', value: 1 },
          { label: '已到期,宽限期内', value: 2 },
          { label: '已到期,锁止', value: 3 },
        ],
      },
      {
        title: '服务是否到期',
        type: 'select',
        key: 'expirationState',
        selectOptions: [
          { label: '否', value: 0 },
          { label: '是', value: 1 },
        ],
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => <span>共&nbsp;{page?.total}&nbsp;条</span>,
    };

    const columns = [
      {
        title: '手持机编号（SN）',
        dataIndex: 'code',
      },
      {
        title: '手持机名称',
        dataIndex: 'name',
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
      {
        title: '手持机服务是否到期',
        dataIndex: 'expirationState',
        render: (text: any) => {
          return expirationState[text];
        },
      },
      {
        title: '手持机服务到期时间',
        dataIndex: 'expirationTime',
      },
      {
        title: '标定状态',
        dataIndex: 'calibrationState',
        render: (text: any) => {
          return calibrationState[text];
        },
      },
      {
        title: '手持机标定到期时间',
        dataIndex: 'calibrationTime',
      },
      {
        title: '手持机闭锁原因',
        dataIndex: 'shuttingReason',
        render: (text: any) => {
          return shuttingReason[text];
        },
      },
      {
        title: '手持机错误原因',
        dataIndex: 'errorReason',
        render: (text: any) => {
          return errorReason[text - 1];
        },
      },
      {
        title: '数据采集时间',
        dataIndex: 'collectTime',
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 150,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'handsetMng_doEdit',
              onConfirm: () => {
                this.handleEdit(record);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'handsetMng_doDel',
              // message: '是否确认删除？',
              // Popconfirm: true,
              onConfirm: () => {
                this.handleDelete(record);
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'HandsetMng/getFetchPage',
              url: '/msalcohollock/handhelds/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            {filterAuth('handsetMng_doAdd', permissions, pathname) ? (
              <Button size="small" type="primary" onClick={this.handleAdd}>
                新增手持机
              </Button>
            ) : null}
            {filterAuth('handsetMng_doExport', permissions, pathname) ? (
              <Button size="small" type="primary" onClick={this.handleExport}>
                批量导入
              </Button>
            ) : null}
          </div>
          <PateoTable
            extraHandle={true}
            currentName={'page'}
            pageSizeName={'size'}
            tableProps={tableProps}
            fetchParams={{ type: 'HandsetMng/getFetchPage', url: '/msalcohollock/handhelds/page' }}
            formValues={formValues}
          />
        </Card>
        <HandleModel
          modalVisible={modalVisible}
          formData={formData}
          closeModal={this.closeModal}
          freshPage={this.handleFreshPage}
        ></HandleModel>
        <ExportModal
          modalVisible={exportVisible}
          closeModal={this.closeExportModal}
          freshPage={this.handleFreshPage}
        ></ExportModal>
        <ConfirmDelModal
          record={checkRecord}
          modalVisible={confirmVisible}
          closeModal={this.closeConfirmModal}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(HandsetMng);
